import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Select, DatePicker, message } from 'antd';
import { useNavigate } from 'react-router-dom';
import { getAssetList, createBorrow, permitUpdate } from '../../../services/api';
import moment from 'moment';

const BorrowForm = () => {
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [assetOptions, setAssetOptions] = useState([]);
  const [currentUser, setCurrentUser] = useState(null);
  const [isAdmin, setIsAdmin] = useState(false);

  useEffect(() => {
    const userInfo = JSON.parse(sessionStorage.getItem('user') || '{}');
    console.log('从sessionStorage获取的用户信息:', userInfo);
    
    if (!userInfo || !userInfo.uId) {
      message.error('用户信息不完整，请重新登录');
      navigate('/login');
      return;
    }
    
    setCurrentUser(userInfo);
    setIsAdmin(userInfo.admin === 'yes');
    fetchAssetList();
  }, []);

  const fetchAssetList = async () => {
    try {
      const response = await getAssetList();
      if (response.code === 200) {
        const options = response.data.map(asset => ({
          label: `${asset.assetName} (可用数量: ${asset.assetNum})`,
          value: asset.assetId,
          assetNum: asset.assetNum
        }));
        setAssetOptions(options);
      }
    } catch (error) {
      console.error('获取资产列表失败:', error);
      message.error('获取资产列表失败');
    }
  };

  const onFinish = async (values) => {
    setLoading(true);
    try {
      const currentTime = moment().format('YYYY-MM-DD');
      
      if (!currentUser || !currentUser.uId) {
        message.error('用户信息不完整，请重新登录');
        navigate('/login');
        return;
      }

      console.log('当前用户信息:', currentUser);
      
      // 检查借用数量是否合法
      const selectedAsset = assetOptions.find(option => option.value === values.assetId);
      if (!selectedAsset) {
        message.error('选择的资产不存在');
        setLoading(false);
        return;
      }

      if (parseInt(values.borrowNum, 10) > selectedAsset.assetNum) {
        message.error('借用数量不能超过可用数量');
        setLoading(false);
        return;
      }

      const borrowData = {
        ...values,
        uId: currentUser.uId,
        borrowTime: currentTime,
        expectedReturnTime: values.expectedReturnTime.format('YYYY-MM-DD'),
        borrowStatus: isAdmin ? '借用中' : '待审批',
        borrowNum: parseInt(values.borrowNum, 10)
      };

      console.log('提交的借用数据:', borrowData);

      const response = await createBorrow(borrowData);
      if (response.code === 200) {
        // 如果是管理员直接借用，更新资产数量
        if (isAdmin) {
          try {
            const updateAssetData = {
              assetId: values.assetId,
              assetNum: borrowData.borrowNum,
              assetStatus: 'lendout'
            };
            const updateResponse = await permitUpdate(values.assetId, updateAssetData);
            if (updateResponse.code !== 200) {
              console.error('更新资产数量失败:', updateResponse);
              message.error(updateResponse.message || '更新资产数量失败，请重试');
              return;
            }
          } catch (error) {
            console.error('更新资产数量时发生错误:', error);
            message.error('系统错误：更新资产数量失败，请重试');
          }
        }
        message.success(isAdmin ? '借用成功' : '借用申请提交成功');
        navigate(isAdmin ? '/admin/borrows' : '/user/borrows');
      } else {
        message.error(response.message || (isAdmin ? '借用失败' : '借用申请提交失败'));
      }
    } catch (error) {
      console.error(isAdmin ? '借用失败:' : '借用申请提交失败:', error);
      message.error(isAdmin ? '借用失败' : '借用申请提交失败');
    }
    setLoading(false);
  };

  return (
    <div style={{ position: 'relative', minHeight: '100vh', padding: '20px' }}>
      {/* 背景图片层 */}
      <div style={{
        position: 'fixed',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        backgroundImage: 'url(/assets/flowers.jpg)',
        backgroundSize: 'cover',
        backgroundPosition: 'center',
        backgroundRepeat: 'no-repeat',
        opacity: 0.8,
        zIndex: 0,
        pointerEvents: 'none'
      }} />

      {/* 内容层 */}
      <div style={{ 
        position: 'relative', 
        zIndex: 1,
        background: 'rgba(255, 255, 255, 0.9)',
        padding: '24px',
        borderRadius: '12px',
        boxShadow: '0 2px 12px rgba(0,0,0,0.1)'
      }}>
        <h2>{isAdmin ? '管理员借用' : '借用申请'}</h2>
        <Form
          form={form}
          layout="vertical"
          onFinish={onFinish}
          style={{ maxWidth: 600 }}
        >
          <Form.Item
            label="资产"
            name="assetId"
            rules={[{ required: true, message: '请选择资产' }]}
          >
            <Select
              placeholder="请选择资产"
              options={assetOptions}
            />
          </Form.Item>

          <Form.Item
            label="借用数量"
            name="borrowNum"
            rules={[
              {
                validator: async (_, value) => {
                  if (!value) {
                    throw new Error('借用数量必须大于0');
                  }
                  const num = parseInt(value, 10);
                  if (isNaN(num) || num <= 0) {
                    throw new Error('借用数量必须大于0');
                  }
                }
              }
            ]}
          >
            <Input type="number" placeholder="请输入借用数量" />
          </Form.Item>

          <Form.Item
            label="预计归还时间"
            name="expectedReturnTime"
            rules={[{ required: true, message: '请选择预计归还时间' }]}
          >
            <DatePicker
              format="YYYY-MM-DD"
              placeholder="请选择预计归还时间"
              style={{ width: '100%' }}
            />
          </Form.Item>

          <Form.Item
            label="借用原因"
            name="borrowReason"
            rules={[{ required: true, message: '请输入借用原因' }]}
          >
            <Input.TextArea
              placeholder="请输入借用原因"
              rows={4}
            />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" loading={loading}>
              {isAdmin ? '直接借用' : '提交申请'}
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};

export default BorrowForm; 